package com.rong.juc_test.juc_p6_p7;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 中断机制
 */
public class InterruptDemo {
    //1. 使用volatile的可见性实现
    // 定义一个volatile变量
    static volatile boolean isStop = false;
    private void interrupt1() {
        new Thread(() -> {
            while (true){
                if (isStop){
                    System.out.println(Thread.currentThread().getName() + "线程已经停止 isStop = " + isStop);
                    break;
                }
                System.out.println("线程执行");
            }
        },"t1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "准备修改isStop");
            isStop = true;
            System.out.println(Thread.currentThread().getName() + "修改isStop = " + isStop);
        },"t2").start();
    }

    // 2. 通过AtomicBoolean实现 底层也是使用volatile修饰
    static AtomicBoolean ato = new AtomicBoolean(false);
    private static void interrupt2() {
        new Thread(() -> {
           while (true){
               if (ato.get()){
                   System.out.println(Thread.currentThread().getName() + "程序停止，ato被修改為" + ato.get());
                   break;
               }
               System.out.println("线程执行");
           }
        },"t1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "准备修改ato");
            ato.set(true);
            System.out.println(Thread.currentThread().getName() + "修改ato = " + ato.get());
        },"t2").start();
    }

    public static void main(String[] args) {
        // 3.使用Thread自带的中断api实现
       Thread t1 =  new Thread(() -> {
            while(true){
                if (Thread.currentThread().isInterrupted()){
                    System.out.println(Thread.currentThread().getName() + "程序停止，isInterrupted被修改為" + Thread.currentThread().isInterrupted());
                    break;
                }
                System.out.println("t1线程执行");
            }
        },"t1");
       t1.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        new Thread(() -> {
//            System.out.println("准备中止t1线程：t2对t1发送一个线程中断的协商");
//            t1.interrupt();// t2对t1发送一个线程中断的协商
//        },"t2").start();
        t1.interrupt(); // 主线程对自己发起一个中断请求
    }
}
